package com.example.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.example.pojo.User;
import com.example.util.Result;
import com.example.util.ThreadLocalUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        System.out.println("执行了拦截器");
        System.out.println(request.getRequestURI());
        response.setContentType("text/html;charset=utf-8");

        //哨兵请求
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }

        if (request.getRequestURI().startsWith("/message")) {
            return true;
        }

        if (request.getRequestURI().startsWith("/interaction/export")) {
            return true;
        }

        if (request.getRequestURI().startsWith("/headline")) {
            return true;
        }

        if (request.getRequestURI().startsWith("/interviewee")) {
            return true;
        }
        if (request.getRequestURI().startsWith("/upload-img")) {
            return true;
        }


        String token = request.getHeader("token");
        System.out.println("token:"+token);
        if (token == null || token.isEmpty()) {
            Result<Object> result = new Result<>("401","权限不够");
            response.getWriter().print(JSONObject.toJSONString(result));
            return false;
        }
        String json=stringRedisTemplate.opsForValue().get(token);
//        System.out.println("json:"+json);
        if (json == null || json.isEmpty()) {
            Result<Object> result = new Result<>("402","token已过期，请重新登录");
            response.getWriter().print(JSONObject.toJSONString(result));
            return false;
        }
        //json->user
        User user = JSONObject.parseObject(json, User.class);
//        request.getSession().setAttribute("currUser", user);
        ThreadLocalUtil.setCurrentId(Long.valueOf(user.getId()));
        return true;
    }
}
